package com.huan.service.impl;

import com.huan.domain.ResponseResult;
import com.huan.domain.entity.User;
import com.huan.domain.entity.loginuser;
import com.huan.service.LoginService;
import com.huan.utils.JwtUtil;
import com.huan.utils.RedisCache;
import com.huan.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) throws Exception {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        loginuser loginuser = (loginuser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginuser.getUser().getId().toString());
        redisCache.setCacheObject("htuserid:"+loginuser.getUser().getId().toString(),loginuser);
//        UserInfoVo infoVo = BeanCopyUtil.resultVO(loginuser.getUser(), UserInfoVo.class);
//        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, infoVo);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);
        ResponseResult result = ResponseResult.okResult(map);
        return result;
    }

    @Override
    public ResponseResult logout() {
        Long id = SecurityUtils.getUserId();
        redisCache.deleteObject("htuserid"+id.toString());
        return ResponseResult.okResult();
    }

//    @Override
//    public ResponseResult logout() {
////        获取userid，并且将获取到的id在redis中删除
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        loginuser loginuser = (com.huan.domain.entity.loginuser) authentication.getPrincipal();
//        Long id = loginuser.getUser().getId();
//        String s = id.toString();
//        boolean b = redisCache.deleteObject("userid:" + s);
//        if (!b){
//            throw  new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
//        }
//
//        return ResponseResult.okResult(200,"操作成功");
//    }
}





















